<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/23
 * Time: 11:12
 */
namespace aes;
class Aes {

    protected static $method = 'AES-128-CBC';#加密方式
    protected static $secret_key = 'Sd2@s.f9)_2o6dpu';#appkey
    protected static $options = 1;#加密等级或者加密的选择项 1 2 3
    private   static $iv= 'f358272e81b2848a';#偏移
    /*public static $objects = null;
    public function __construct()
    {
        if(!self::$objects instanceof self){
            self::$objects = new self();
        }
        return self::$objects;
    }*/

    /**对称加密
     * @param $input
     * @return array
     */
    public static function encrypt($input) {
        $ivlen = openssl_cipher_iv_length(self::$method);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $iv = bin2hex($iv);
        if(strlen($iv) > $ivlen) {
            $iv = substr($iv, 0, $ivlen);
        }
        $sign = openssl_encrypt(json_encode($input), self::$method, self::$secret_key, self::$options, $iv);
        $sign = base64_encode($sign);
        $signdata = ['sign' => $sign, 'iv' => $iv];
        return $signdata;
    }
    /**对称解密
     * @param $sign
     * @param $iv
     * @return false|string
     */
    public static function decrypt($sign, $iv) {
        return openssl_decrypt(base64_decode($sign), self::$method, self::$secret_key, self::$options, $iv);

    }

    /**对称加密返回自渡船
     * @param $input
     * @return array
     */
    public static function arrEncrypt($input)
    {
        $sign = openssl_encrypt(json_encode($input), self::$method, self::$secret_key, self::$options, self::$iv);
        $sign = base64_encode($sign);
        return $sign;
    }

    /**对称解密
     * @param $sign
     * @param $iv
     * @return false|string
     */
    public static function arrDecrypt($sign)
    {
        return openssl_decrypt(base64_decode($sign), self::$method, self::$secret_key, self::$options, self::$iv);

    }

    /**
     * 字符串加密
     * @param string $input
     * @return string
     */
    public static function strEncrypt(string $input)
    {
        $sign = openssl_encrypt($input, self::$method, self::$secret_key, self::$options, self::$iv);
        return base64_encode($sign);
    }

    /**
     * 字符串解密
     * @param string $sign
     * @return false|string
     */
    public static function strDecrypt(string $sign)
    {
        return openssl_decrypt(base64_decode($sign), self::$method, self::$secret_key, self::$options, self::$iv);
    }
}

